const app = getApp()
const { category, courseList} = require('../../api/course')
const { API_OK } = require('../../utils/setting')

Page({
  data: {
    stickyTop: app.globalData.headerHeight,
    loading: false,
    keyword: '',
    tabs: [],
    activeTabIndex: 0,
    sortLabels: [
      { label: '综合', value: 'all', sort: false },
      { label: '销量', value: 'sales', sort: true, status: 0 },
      { label: '新品', value: 'new', sort: true, status: 0 },
      { label: '积分', value: 'price', sort: true, status: 0 }
    ],
    activeSortIndex: 0,
    courses: []
  },
  pageData: {
    page: 1,
    canLoadMore: true
  },
  async onLoad() {
    wx.showLoading({ title: '拼命加载中', mask: true })
    this.setData({ loading: true })
    await this.getTabs()
    this.getCourses()
  },
  onReachBottom() {
    if (!this.pageData.canLoadMore) return
    this.pageData.page += 1
    this.setData({ loading: true })
    this.getCourses()
  },
  async onPullDownRefresh() {
    this.pageData.canLoadMore = true
    this.pageData.page = 1
    this.setData({ loading: true, courses: [], tabs: [] })
    await this.getTabs()
    this.getCourses()
  },
  /**
   * 重置查询课程的搜索条件
   */
  resetConditions() {
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      sortLabels: [
        { label: '综合', value: 'all', sort: false },
        { label: '销量', value: 'sales', sort: true, status: 0 },
        { label: '新品', value: 'new', sort: true, status: 0 },
        { label: '积分', value: 'price', sort: true, status: 0 }
      ],
      activeSortIndex: 0,
      activeTabIndex: 0
    })
  },
  /**
   * 切换课程分类
   */
  changeTabIndex({detail: {name}}) {
    // console.log(name)
    this.setData({ activeTabIndex: name, loading: true, courses: [] })
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.getCourses()
  },
  /**
   * 修改选中的排序
   */
  changeActiveIndex({detail}) {
    if (this.data.activeSortIndex === detail.index) return
    const lastIndexLabel = this.data.sortLabels[this.data.activeSortIndex]
    lastIndexLabel.sort && (lastIndexLabel.status = 0)
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      activeSortIndex: detail.index,
      sortLabels: this.data.sortLabels,
      loading: true,
      courses: []
    }, () => {
      this.getCourses()
    })
  },
  /**
   * 修改排序规则
   */
  changeSortStatus({detail}) {
    const target = this.data.sortLabels[detail.index]
    target.status = target.status === 0 ? 1 : 0
    this.pageData.page = 1
    this.pageData.canLoadMore = true
    this.setData({
      sortLabels: this.data.sortLabels,
      loading: true,
      courses: []
    }, () => {
      this.getCourses()
    })
  },
  /**
   * 修改搜索关键字
   */
  changeKeyword({detail: {value}}) {
    this.setData({ keyword: value })
  },
  /**
   * 搜索课程
   */
  search() {
    this.resetConditions()
    this.setData({ loading: true, courses: [] })
    this.getCourses()
  },
  /**
   * 获取课程分类
   */
  getTabs() {
    category({ callback: wx.hideLoading }).then(res => {
      // console.log(res)
      if (res.code === API_OK) {
        const category = res.data.list.map(item => ({ id: item.cate_course_id, name: item.cate_course_name }))
        category.unshift({id: 0, name: '全部'})
        const currentTab = category.filter(item => item.id === this.data.activeTabIndex)
        const index = currentTab.length ? this.data.activeTabIndex : 0
        this.setData({ tabs: category, activeTabIndex: index })
      }
    })
    .catch(err => {
      console.warn(err)
      this.setData({ loading: false })
    })
  },
  /**
   * 获取课程列表
   */
  getCourses() {
    courseList({
      data: {
        category_id: this.data.activeTabIndex,
        sortType: this.data.sortLabels[this.data.activeSortIndex].value,
        sortPrice: this.data.sortLabels[this.data.activeSortIndex].status || 0,
        search: this.data.keyword,
        page: this.pageData.page,
        paginate: 15
      }
    })
    .then(res => {
      wx.stopPullDownRefresh()
      console.log(res)
      if (res.code === API_OK) {
        this.pageData.canLoadMore = res.data.current_page < res.data.last_page
        this.setData({
          loading: false,
          courses: res.data.data.map(item => {
            return {
              id: item.courses_id,
              image: (item.image && item.image.length) && item.image[0].file_path,
              courseName: item.course_name,
              classHour: item.lessons_count,
              purchasedNum: item.sold_count,
              coursePrice: item.course_price,
              credit: item.score_deduct * 1
            }
          })
        })
      }
    })
    .catch(err => {
      console.warn(err)
      wx.stopPullDownRefresh()
      this.setData({ loading: false })
    })
  }
})
